﻿#region Usings

using System;
using System.Collections.Generic;
using FeedReader;
using FeedReader.Data;
using InfoService.BackgroundWorkers;
using InfoService.Feeds;
using InfoService.GUIWindows;
using MediaPortal.GUI.Library;

#endregion

namespace InfoService.Utils
{
    public static class FeedUtils
    {
        private static readonly Logger logger = Logger.GetInstance();

        public static void SetAllFeedsOnBasichome()
        {
            int safeIndex = FeedService.SetActive(0);
            if (safeIndex == 0)
            {
                InfoServiceUtils.SetProperty("#infoservice.feed.isalltitles", "true");
                InfoServiceUtils.SetProperty("#infoservice.feed.titles",MakeFeedMixLine(FeedService.Feeds[0], FeedService.Items,FeedService.Separator));
                InfoServiceUtils.SetProperty("#infoservice.feed.alltitles",MakeFeedMixLine(FeedService.Feeds[0], FeedService.Items,FeedService.Separator));
                InfoServiceUtils.SetProperty("#infoservice.feed.img",GUIGraphicsContext.Skin + @"\media\InfoService\defaultFeedALL.png");
                logger.WriteLog("Set all feeds on basichome", LogLevel.Debug, InfoServiceModul.Feed);
            }
            else
            {
                logger.WriteLog("Failed to set all feeds ticker on basichome... Returning to fallback feed index -> " + safeIndex, LogLevel.Warning, InfoServiceModul.Feed);
            }
        }

        public static void SetFeedOnBasichome(int index)
        {
            if(index == 0)
            {
                SetAllFeedsOnBasichome();
                return;
            }
            int safeIndex = FeedService.SetActive(index);
            if (safeIndex == index)
            {
                InfoServiceUtils.SetProperty("#infoservice.feed.isalltitles", "false");
                InfoServiceUtils.SetProperty("#infoservice.feed.titles", MakeFeedLine(FeedService.Feeds[FeedService.ActiveFeedIndex], FeedService.TickerMask, FeedService.Items, FeedService.Separator));
                InfoServiceUtils.SetProperty("#infoservice.feed.alltitles", MakeFeedMixLine(FeedService.Feeds[0], FeedService.Items, FeedService.Separator));
                InfoServiceUtils.SetProperty("#infoservice.feed.img", FeedService.Feeds[FeedService.ActiveFeedIndex].ImagePath);
                logger.WriteLog("Set feed[" + FeedService.Feeds[FeedService.ActiveFeedIndex].Title + "]/[" + FeedService.ActiveFeedIndex + "] on basichome", LogLevel.Debug, InfoServiceModul.Feed);
            }
            else
            {
                logger.WriteLog("Failed to set feed[" + index + "] on basichome... Returning to fallback feed index -> " + safeIndex, LogLevel.Warning, InfoServiceModul.Feed);
            }
        }

        public static void SetFeedOnWindow(int index)
        {
            InfoServiceUtils.SetProperty("#infoservice.feed.selected.feed", FeedService.Feeds[index].Title);
            InfoServiceUtils.SetProperty("#infoservice.feed.selected.type", FeedService.Feeds[index].Type.ToString());
            InfoServiceUtils.SetProperty("#infoservice.feed.itemcount", MediaPortal.Util.Utils.GetObjectCountLabel(FeedService.Feeds[index].Items.Count));

            GUIListControl.ClearControl(GUIFeed.GUIFeedId, GUIFeed.GUIFeedList);
            if (FeedService.Feeds[index].Items.Count > 0)
            {
                InfoServiceUtils.SetProperty("#infoservice.feed.selected.itemimg", FeedService.Feeds[index].Items[0].ImagePathBig);
                InfoServiceUtils.SetProperty("#infoservice.feed.selected.title", FeedService.Feeds[index].Items[0].Title);
                GUIControl.SetControlLabel(GUIFeed.GUIFeedId, GUIFeed.GUIFeedDescription, FeedService.Feeds[index].Items[0].Description);
                
                for (int i = 0; i < FeedService.Feeds[index].Items.Count; i++)
                {

                    GUIListItem item = new GUIListItem
                    {
                        IconImage = FeedService.Feeds[index].Items[i].ImagePath,
                        Label = FeedService.Feeds[index].Items[i].Title
                    };
                    
                    if (FeedService.ShowPublishTime)
                    {
                        if (!FeedService.Feeds[index].IsAllFeed)
                        {
                            item.Label2 = InfoServiceUtils.GetTimeDifferenceToNow(FeedService.Feeds[index].Items[i].PublishDate);
                            logger.WriteLog("Set/Calc time difference for feed[" + FeedService.Feeds[index].Title + "]/[" + index + "]. For " + FeedService.Feeds[index].Items[i].PublishDate + " its \"" + item.Label2 + "\"", LogLevel.Debug, InfoServiceModul.Feed);
                        }
                        else
                        {
                            item.Label2 = FeedService.Feeds[index].Items[i].SourceTitle;
                        }
                    }
                    GUIListControl.AddListItemControl(GUIFeed.GUIFeedId, GUIFeed.GUIFeedList, item);
                    //listControl.Add(item);
                }
                logger.WriteLog("Set feed[" + FeedService.Feeds[index].Title + "]/[" + index + "] on window", LogLevel.Debug, InfoServiceModul.Feed);
            }
            else
            {
                InfoServiceUtils.SetProperty("#infoservice.feed.selected.itemimg", " ");
                InfoServiceUtils.SetProperty("#infoservice.feed.selected.title", " ");
                GUIControl.SetControlLabel(GUIFeed.GUIFeedId, GUIFeed.GUIFeedDescription, "");
            }
        }

        public static string MakeFeedLine(ExFeed feed, string mask, int items, string separator)
        {
            if(feed == null) return "";
            logger.WriteLog("Make feed[" + feed.Title + "] line with mask " + mask, LogLevel.Debug, InfoServiceModul.Feed);
            if (feed.Items.Count > 0)
            {
                string _feedAsLine = String.Empty;
                int _feedCounter = 0;
                foreach (ExFeedItem item in feed.Items)
                {
                    _feedAsLine += ReplaceTickerMask(feed, mask, _feedCounter) + " " + separator + " ";
                    if (_feedCounter >= items - 1)
                    {
                        break;
                    }
                    _feedCounter++;
                }
                if (_feedAsLine.Length >= separator.Length + 1) _feedAsLine = _feedAsLine.Substring(0, _feedAsLine.Length - separator.Length - 2);
                return _feedAsLine;
            }
            return "";
        }

        public static string ReplaceTickerMask(ExFeed feed, string mask, int itemnumber)
        {
            if (feed == null) return "";
            if (feed.Items.Count <= 0) return "";
            string newText = mask;


            newText = newText.Replace("%feedtitle%", feed.Title);
            newText = newText.Replace("%feeddescription%", feed.Description);
            newText = newText.Replace("%itemtitle%", feed.Items[itemnumber].Title);
            newText = newText.Replace("%itemdescription%", feed.Items[itemnumber].Description);
            newText = newText.Replace("%author%", feed.Items[itemnumber].Author);
            newText = newText.Replace("%d%", feed.Items[itemnumber].PublishDate.ToString("d ").Substring(0, feed.Items[itemnumber].PublishDate.ToString("d ").Length - 1));
            newText = newText.Replace("%dd%", feed.Items[itemnumber].PublishDate.ToString("dd"));
            newText = newText.Replace("%M%", feed.Items[itemnumber].PublishDate.ToString("M ").Substring(0, feed.Items[itemnumber].PublishDate.ToString("M ").Length - 1));
            newText = newText.Replace("%MM%", feed.Items[itemnumber].PublishDate.ToString("MM"));
            newText = newText.Replace("%yy%", feed.Items[itemnumber].PublishDate.ToString("yy"));
            newText = newText.Replace("%yyyy%", feed.Items[itemnumber].PublishDate.ToString("yyyy"));
            newText = newText.Replace("%h%", feed.Items[itemnumber].PublishDate.ToString("h ").Substring(0, feed.Items[itemnumber].PublishDate.ToString("h ").Length - 1));
            newText = newText.Replace("%hh%", feed.Items[itemnumber].PublishDate.ToString("hh"));
            newText = newText.Replace("%H%", feed.Items[itemnumber].PublishDate.ToString("H ").Substring(0, feed.Items[itemnumber].PublishDate.ToString("H ").Length - 1));
            newText = newText.Replace("%HH%", feed.Items[itemnumber].PublishDate.ToString("HH"));
            newText = newText.Replace("%m%", feed.Items[itemnumber].PublishDate.ToString("m ").Substring(0, feed.Items[itemnumber].PublishDate.ToString("m ").Length - 1));
            newText = newText.Replace("%mm%", feed.Items[itemnumber].PublishDate.ToString("mm"));
            newText = newText.Replace("%s%", feed.Items[itemnumber].PublishDate.ToString("s ").Substring(0, feed.Items[itemnumber].PublishDate.ToString("s ").Length - 1));
            newText = newText.Replace("%ss%", feed.Items[itemnumber].PublishDate.ToString("ss"));
            return newText;

        }

        public static string MakeFeedMixLine(ExFeed feed, int items, string separator)
        {
            if (feed == null) return "";
            if (feed.Items.Count <= 0) return "";
            logger.WriteLog("Make feed mix line", LogLevel.Debug, InfoServiceModul.Feed);
            string mixfeedline = String.Empty;

            int _feedCounter = 0;
            foreach (ExFeedItem item in feed.Items)
            {
                mixfeedline += item.Title + " (" + item.SourceTitle + ") " + separator + " ";
                if (_feedCounter >= items + 1)
                {
                    break;
                }
                _feedCounter++;
            }
            if (mixfeedline.Length >= separator.Length + 1) mixfeedline = mixfeedline.Substring(0, mixfeedline.Length - separator.Length - 2);
            return mixfeedline;
        }



        /*
                private void ShowUpdatingDialog()
                {
                    _dialogUpdateNotify = (GUIDialogNotify)GUIWindowManager.GetWindow((int)Window.WINDOW_DIALOG_NOTIFY);
                    _dialogUpdateNotify.TimeOut = 8;
                    _dialogUpdateNotify.SetImage(GUIGraphicsContext.Skin + @"\media\InfoService\UpdateLogo.png");
                    _dialogUpdateNotify.SetHeading("InfoService");
                    _dialogUpdateNotify.SetText("Updating Feeds/Weather/Twitter...");
                    _dialogUpdateNotify.DoModal(GUIWindowManager.ActiveWindow);
                }
        */


        public static void UpdateFeedDataAsync()
        {
            if (FeedService.Enabled)
            {
                if (FeedService.UpdateInProgress)
                    return;

                InfoServiceUtils.DeleteFeedCache();
                InfoServiceUtils.SetProperty("#infoservice.feed.titles", InfoServiceUtils.GetLocalizedLabel(13));
                InfoServiceUtils.SetProperty("#infoservice.feed.alltitles", InfoServiceUtils.GetLocalizedLabel(13));
                FeedWorker fWorker = new FeedWorker();
                fWorker.RunWorkerCompleted += fWorker_RunWorkerCompleted;
                fWorker.RunWorkerAsync();
            }
        }

        public static void UpdateFeedDataSync()
        {
            if (FeedService.Enabled)
            {
                if (FeedService.UpdateInProgress)
                    return;

                InfoServiceUtils.DeleteFeedCache();
                InfoServiceUtils.SetProperty("#infoservice.feed.titles", InfoServiceUtils.GetLocalizedLabel(13));
                InfoServiceUtils.SetProperty("#infoservice.feed.alltitles", InfoServiceUtils.GetLocalizedLabel(13));
                if (FeedService.UpdateAllFeeds())
                {
                    SetFeedProperties(true);
                }
                else
                {
                    SetFeedProperties(false);
                }
            }

        }

        private static void SetFeedProperties(bool success)
        {
            if (!success)
            {
                InfoServiceUtils.SetProperty("#infoservice.feed.titles", InfoServiceUtils.GetLocalizedLabel(14));
                InfoServiceUtils.SetProperty("#infoservice.feed.alltitles", InfoServiceUtils.GetLocalizedLabel(14));
            }
            else
            {
                int index = 0;
                if (FeedService.MediaPortalStartup)
                {

                    if (!FeedService.RandomFeedOnStartup)
                    {
                        index = FeedService.StartupFeedIndex;
                    }
                    else
                    {
                        Random rnd = new Random();
                        index = rnd.Next(0, FeedService.Feeds.Count - 1);
                    }
                    FeedService.MediaPortalStartup = false;
                }
                else
                {
                    if (!FeedService.RandomFeedOnUpdate)
                    {
                        index = FeedService.ActiveFeedIndex;
                    }
                    else
                    {
                        Random rnd = new Random();
                        index = rnd.Next(0, FeedService.Feeds.Count - 1);
                    }

                }
                SetFeedOnBasichome(index);
                SetFeedOnWindow(index);
                InfoServiceUtils.SetProperty("#infoservice.feed.lastupdated.message", string.Format(InfoServiceUtils.GetLocalizedLabel(29), FeedService.LastRefresh));
                InfoServiceUtils.SetProperty("#infoservice.feed.lastupdated.datetime", FeedService.LastRefresh.ToString());
            }
        }
        static void fWorker_RunWorkerCompleted(object sender, System.ComponentModel.RunWorkerCompletedEventArgs e)
        {
            if (e.Cancelled || !(bool)e.Result)
            {
                SetFeedProperties(false);
            }
            else SetFeedProperties(true);
        }
    }
}
